package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/common")
@RestController
public class CommonController {

    @Value("${reggie.filePath}")
    private String filePath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        UUID uuid = UUID.randomUUID();

        file.transferTo(new File(filePath+uuid+substring));

        return R.success(uuid+substring);
    }

    @GetMapping("/download")
    public R download(String name, HttpServletResponse response){
        try {
            //PrintWriter writer = response.getWriter();
            ServletOutputStream outputStream = response.getOutputStream();
            //response.setContentType("image/jpeg");
            FileInputStream fileInputStream = new FileInputStream(new File(filePath,name));
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return R.success("添加成功");
    }


}
